package allrobots.RobotThread;

import allrobots.DispensingMachine.DMAndRobotOosOis;
import allrobots.DispensingMachine.DMAndRobotSocket;
import allrobots.DispensingMachine.DispensingMachinePosition;
import allrobots.Robot.RobotMessage;
import allrobots.Robot.RobotMessageMap;
import allrobots.Robot.RobotsSocketMap;
import allrobots.TraceAndAvoid.Move;
import allrobots.TraceAndAvoid.Route;
import allrobots.pojo.BroadcastMessage;
import allrobots.sendMessages.ChangeStatus.ChangeRobot;
import allrobots.sendMessages.RobotAndDM.SendOrder;
import t10086.Data.Broadcast;
import t10086.Data.Map.TextCoordinate;
import t10086.Data.Robot.RobotStatus;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

class ClientHandler implements Runnable {
    private Integer robotId;
    private Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;
    private String clientAddress;

    public ClientHandler(Integer robotId,Socket socket) {
        this.robotId=robotId;
        this.socket = socket;
        this.clientAddress = socket.getRemoteSocketAddress().toString();
        try {
            this.in = new ObjectInputStream(socket.getInputStream());
            this.out = new ObjectOutputStream(socket.getOutputStream());
            DMAndRobotSocket.put(RobotMessageMap.robotMap.get(robotId).getSerialNum(),new DMAndRobotOosOis(out,in,socket));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true){
                if(socket!=null){
                    Object listenMessage = in.readObject();
                    if (listenMessage != null) {
                        Message message = (Message) listenMessage;
                        //如果发来的消息是发药机，移动
                        if (message.getType().equals(MessageType.DISPENSING_MESSAGE)) {
                            //申请状态转换
                            System.out.println("移动前状态转换申请");
                            RobotMessage robot = RobotMessageMap.robotMap.get(robotId);
                            Message statusChange = new Message(MessageType.STATUS_EXCHANGE, new ChangeRobot(robot.getSerialNum(), robot.getRobotStatus(), RobotStatus.MOVING, null));
                            System.out.println(RobotsSocketMap.robotsSocketMap.size());
                            statusChange.setSender((InetSocketAddress) RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getLocalSocketAddress());
                            statusChange.setReceiver((InetSocketAddress) RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getRemoteSocketAddress());
                            RobotsSocketMap.robotsSocketMap.get(robotId).getOos().writeObject(statusChange);
                            RobotsSocketMap.robotsSocketMap.get(robotId).getOos().flush();
                            System.out.println("移动前状态转换申请完成");
                            //改变最终位置
                            RobotMessage robot1 = RobotMessageMap.robotMap.get(robotId);
                            robot1.setTermination(DispensingMachinePosition.windowPosition);

                            robot1.setRobotStatus(RobotStatus.MOVING);
                            RobotMessageMap.setRobotMessage(robotId, robot1);
                            System.out.println("重点目的地已经改变");
                            //改变终点后开始移动
                            new Thread(new RegularReplies(robotId, socket)).start();//表示是发药机
                        } else if (message.getType().equals(MessageType.ORDER_INFO)) {
                            SendOrder order = message.convertData(SendOrder.class);
                            System.out.println("机器人收到的订单号是" + order.getOrder());
                            RobotMessage robot = RobotMessageMap.robotMap.get(robotId);
                            robot.setOrder(order.getOrder());
                            Move move=new Move(socket,robotId);
                            move.decideTermination();
                            robot.startTime= System.currentTimeMillis();
                            RobotMessageMap.setRobotMessage(robotId, robot);
                            DMAndRobotSocket.remove(robot.getSerialNum());
                            System.out.println("机器人"+robot.getSerialNum()+"收到发药机订单");
                            out.close();;
                            out=null;
                            in.close();
                            in=null;
                            socket=null;
                        }
                    }
                }
            }
        } catch (IOException | ClassNotFoundException ignored) {
        } finally {
            // 客户端断开连接时，从客户端管理Map中移除
            Connected.clientMap.remove(clientAddress);
        }
    }
}